package edu.gyc.mysystem.controller;

import edu.gyc.mysystem.dao.RoleMapper;
import edu.gyc.mysystem.dao.UserMapper;
import edu.gyc.mysystem.model.Role;
import edu.gyc.mysystem.model.User;
import edu.gyc.mysystem.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    RoleService roleService;
    @Autowired
    RoleMapper roleMapper;

    @RequestMapping("/query")
    public String query(Model model) {
        List<Role> roles = roleMapper.getRoles();
        model.addAttribute("roles", roles);
        return "/admin/role";
    }

    @RequestMapping("/queryperms")
    public String queryperms(Integer id, Model model) {

        Role role = roleMapper.selectByPrimaryKey(id);
        model.addAttribute("roleId", id);
        model.addAttribute("roleName", role.getDescription());

        model.addAttribute("myperms", roleService.getPermsByRoleId(id));
        return "/admin/myperms";
    }

    @PostMapping("/updateRolePermissions")
    public String form1(String[] acquireId, Integer roleId, Model model) {
        String a = Arrays.toString(acquireId);
        List<Integer> ids = new ArrayList<>();
        if (acquireId.length > 0) {
            for (String id : acquireId) {
                ids.add(Integer.parseInt(id));
            }
        }

        roleService.updateRolePermissions(roleId, ids);


        model.addAttribute("qxmsg", "角色权限更新成功！");
        model.addAttribute("roleId", roleId);

        return "/admin/permmsg";
    }

    @Autowired
    UserMapper userMapper;
    @GetMapping("/addUser")
    public String addUser(Integer rid, Model model) {
        Role role = roleMapper.selectByPrimaryKey(rid);
        List<User> users=userMapper.getUsers();
        model.addAttribute("role", role);
        model.addAttribute("users", users);
        return "/admin/roleuser";
    }

    @PostMapping("/addUser")
    public String doaddUser(Integer rid, Integer uid,Model model) {
      boolean r =  roleService.addUser(rid,uid);
        String msg = "";
      if(r){
          msg = "添加角色成功";
      }else {
          msg = "已拥有该角色";
      }

        model.addAttribute("msg", msg);
        return "/admin/rolemsg";
    }
}
